﻿using Newtonsoft.Json;
using RentHouse.DTO;
using RentHouse.IService;
using RentHouse.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using static NPOI.HSSF.Util.HSSFColor;
using System.Web.UI;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Xml.Linq;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Formula.PTG;

namespace RentHouse.Admin.Controllers
{
    /// <summary>
    /// 房屋管理控制器
    /// </summary>
    public class HousesController : Controller
    {
        IHousesService housesService;

        public HousesController(IHousesService housesService)
        {
            this.housesService = housesService;
        }



        public string aaa()
        {
            //Response.Headers.Add("Access-Control-Allow-Origin", "*");
            if (1 == 1)
            {
                return "success";
            }
        }


        /// <summary>
        /// 获取房屋列表
        /// </summary>
        /// <returns></returns>
        public string GetList(int page, int limit)
        {
            //Response.Headers.Add("Access-Control-Allow-Origin", "*");
            //字典类（用于存储数据）
            Dictionary<string, object> map = new Dictionary<string, object>();

            List<HousesDTO> list = housesService.GetList();
            map.Add("code", "0");//数据格式或类型
            map.Add("msg", "用户列表信息");//数据声明
            map.Add("count", list.Count);//数据总数（用于分页）

            map.Add("data", list
            .OrderBy(u => u.Id)//分页前必须根据某一列进行排序，保证数据顺序唯一
                .Skip((page - 1) * limit)//执行当前页起始数据
                .Take(limit));//每页条数

            return JsonConvert.SerializeObject(map);
        }

        /// <summary>
        /// 房屋图片上传
        /// </summary>
        /// <param name="file"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpPost]
        public string Update(HttpPostedFileBase file, string Id)
        {

            //Response.Headers.Add("Access-Control-Allow-Origin", "*");

            //文件上传（上传到指定位置）
            //判断文件是否为空
            if (file != null)
            {
                //file
                //获取文件名
                string fileName = file.FileName;
                //获取文件后缀（扩展名）
                string fileExt = Path.GetExtension(fileName);
                if (fileExt == ".jpg" || fileExt == ".png" || fileExt == ".jpeg" || fileExt == ".gif")
                {
                    //获取本地路径
                    string pathFile = Server.MapPath("~/" + "File");

                    if (!Directory.Exists(pathFile))
                    {
                        //若该路径不存在，则创建该路径
                        Directory.CreateDirectory(pathFile);
                    }
                    //将文件名称进行随机命名
                    fileName = Guid.NewGuid().ToString("N") + fileExt;
                    //将上传文件保存到指定路径
                    file.SaveAs(Path.Combine(pathFile, fileName));

                    //获取数据名称获取到上传的文件名（存储到数据库）
                    return housesService.Update(int.Parse(Id), fileName);

                }
                else
                {
                    return "error";
                }

            }
            else
            {
                return "error";
            }

        }

        /// <summary>
        /// 房屋信息批量上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public string AddAll(HttpPostedFileBase file, string token)
        {

            //Response.Headers.Add("Access-Control-Allow-Origin", "*");
            // 判断文件是否为空
            if (file != null)
            {
                // 保存文件后缀
                string Frelsuffix = Path.GetExtension(file.FileName);
                if (Frelsuffix == ".xls" || Frelsuffix == ".xlsx")
                {
                    //创建一个工作簿对象(用于读取excel文件)
                    IWorkbook workbook = null;
                    if (Frelsuffix == ".xls")
                    {
                        //后缀是xls就用HSSFWorkbook
                        workbook = new HSSFWorkbook(file.InputStream);
                    }
                    else if (Frelsuffix == ".xlsx")
                    {
                        //后缀是xlsx就用XSSFWorkbook(最后是x就用XSSFWorkbook)
                        workbook = new XSSFWorkbook(file.InputStream);
                    }

                    int number = 0;

                    //获取第一张表格
                    ISheet sheet = workbook.GetSheetAt(0);

                    if (sheet.LastRowNum > 0)
                    {
                        for (int i = 0; i < sheet.LastRowNum; i++)
                        {

                            //获取第一行
                            IRow row = sheet.GetRow(i + 1);

                            HousesDTO housesDTO = new HousesDTO()
                            {
                                Name = row.GetCell(0).ToString(),
                                CommunityId = row.GetCell(1).ToString(),
                                Address = row.GetCell(2).ToString(),
                                MonthRent = row.GetCell(3).ToString(),
                                RoomTypeId = row.GetCell(4).ToString(),
                                DecorateStatusId = row.GetCell(5).ToString(),
                                Area = row.GetCell(6).ToString()
                            };

                            number += housesService.Create(housesDTO);
                        }
                        if (number > 0 && number == sheet.LastRowNum)
                        {
                            return "success";
                        }
                        else
                        {
                            return "error";
                        }
                    }
                    else
                    {

                        return "error";
                    }
                }
                else
                {

                    return "error";
                }


            }
            else
            {
                // 上传失败
                return "error";
            }
        }

    }
}